/**
 * Created by Administrator on 14-3-18.
 */
var mongoose = require('mongoose')
  , Article = mongoose.model('Article');

/**
 * 文章列表
 * @param req
 * @param res
 */
exports.list = function(req, res) {
  var page = (req.query.p > 0 ? req.query.p : 1) - 1
    , perPage = 10
    , render = {
      title : "文章列表"
    }
    , options = {
      perPage : perPage,
      page : page,
      sort : {createdAt : -1}
    };

  //读取文章
  Article.list(options, function(err, list){
    render.articleList = list;
    Article.count().exec(function(err, count) {
      if(err) console.log(err);
      render.page = page +1;
      render.pages = Math.ceil(count/perPage);
      render.count = count;
      if((page+1)>render.pages) res.redirect('/article/list');
      res.render('admin/article/list', render);
    });
  });
}

/**
 * 添加文章
 * @param req
 * @param res
 */
exports.add = function(req, res) {
  var render = {
    title : "文章添加",
    article : new Article({})
  };

  res.render('admin/article/add', render);
}

/**
 * 编辑文章
 * @param req
 * @param rs
 */
exports.edit = function(req, res) {
  var id = req.params.id;
  Article.load(id, function (err, article) {
    if (err || !article) {
      res.send('not found');
      return err;
    }
    res.render('admin/article/edit', {title : article.title, article : article});
  })
}

/**
 * 删除文章
 * @param req
 * @param res
 */
exports.delete = function(req, res) {
  res.render('admin/article/delete');
}

/**
 * 更新文章
 * @param req
 * @param res
 */
exports.update = function(req, res) {
  if (req.body.id) {
    Article.update({ _id: req.body.id}, req.body, function(err, numberAffect) {
      if (err) {
        res.json({msg : '保存失败'});
        return;
      }
      numberAffect && res.json({success : 1});
    });
  } else {
    var article = new Article(req.body);

    article.save(function(err){
      if (err) res.json(err.errors.body)
      else res.json({success : 1});
    });
  }
}